import { Effect } from 'dva';
import { Reducer } from 'redux';
// import { setToken, deleteToken } from '@/utils/auth';
import { getToken, getUserInfo } from '@/services/user';
import Event from '@/utils/event';
import { Toast } from 'antd-mobile-v2';
import { SUCCESS_CODE } from '@/services/constant';
export interface IResUserInfo {
  id: string;
  userName: string;
  password: string;
  mobile: string;
  icon: string;
  email: string;
  orgId: string;
  status: number;
  sortNo: number;
  remark: string;
  crtTime: string;
  updUserName: string;
  updUserId: string;
  updTime: string;
  tenantId: string;
  superAdmin: number;
  department: string;
  postId: string;
  postName: string;
  isAdmin: number;
}

export interface UserState {
  loginStatus?: number;
  userinfo?: IResUserInfo;
}
export interface IUserModel {
  namespace: 'user';
  state: UserState;
  effects: {
    getToken: Effect; // 获取申请单
    getUserInfo: Effect;
  };
  reducers: {
    saveToken: Reducer<UserState>;
    saveUserInfo: Reducer<UserState>;
    changeLoginStatus: Reducer<UserState>;
  };
  subscriptions: {
    listenLoginStatus: (params: any) => () => void;
  };
}

const UserModel: IUserModel = {
  namespace: 'user',
  state: {},
  effects: {
    * getToken({ payload }, { call, put }) {
      // deleteToken();
      const response = yield call(getToken, payload) || {};
      const { status, data } = response;
      if (status === SUCCESS_CODE) {
        yield put({
          type: 'saveToken',
          payload: data
        });
        yield put({
          type: 'changeLoginStatus',
          payload: status
        });
      }
      return response;
    },
    * getUserInfo({ payload }, { call, put }) {
      const response = yield call(getUserInfo, payload) || {};
      const { status, data } = response;
      if (status === SUCCESS_CODE) {
        yield put({
          type: 'saveUserInfo',
          payload: data
        });
      }
      return response;
    }
  },
  reducers: {
    saveToken(state, { payload }) {
      // setToken(payload);
      return {
        ...state
      };
    },
    saveUserInfo(state, { payload }) {
      return {
        ...state,
        userinfo: payload
      };
    },
    changeLoginStatus(state, { payload }) {
      if (state?.loginStatus == payload) {
        return { ...state };
      }
      if (payload === 401) {
        Toast.info('审批接口401');
      }
      return {
        ...state,
        loginStatus: payload
      };
    }
  },
  subscriptions: {
    listenLoginStatus(params) {
      const dispatch = params.dispatch;
      const handler = (_a: any, status: number) => {
        dispatch({ type: 'changeLoginStatus', payload: status });
      };
      Event.on('ChangeLoginStatus', handler);
      return () => {
        Event.off('ChangeLoginStatus', handler);
      };
    }
  }
};

export default UserModel;
